/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.monitor.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.config.ApplicationTask;
import org.springblade.modules.desk.entity.Alerts;
import org.springblade.modules.desk.mapper.AlertsMapper;
import org.springblade.modules.monitor.entity.Application;
import org.springblade.modules.monitor.entity.ChainRelationship;
import org.springblade.modules.monitor.entity.ChainSource;
import org.springblade.modules.monitor.mapper.ChainRelationshipMapper;
import org.springblade.modules.monitor.mapper.ChainSourceMapper;
import org.springblade.modules.monitor.service.IChainRelationshipService;
import org.springblade.modules.monitor.vo.ChainRelationshipVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

import static org.springblade.common.tool.CommonUtil.getDefaultAlert;

/**
 *  服务实现类
 *
 * @author Blade
 * @since 2020-08-18
 */
@Service
public class ChainRelationshipServiceImpl extends ServiceImpl<ChainRelationshipMapper, ChainRelationship> implements IChainRelationshipService {

	@Autowired
	private ChainRelationshipMapper chainRelationshipMapper;
	@Autowired
	private AlertsMapper alertsMapper;
	@Autowired
	private ChainSourceMapper chainSourceMapper;

	private static final Logger LOGGER =  LoggerFactory.getLogger(ChainRelationshipServiceImpl.class);
	@Override
	public IPage<ChainRelationshipVO> selectChainRelationshipPage(IPage<ChainRelationshipVO> page, ChainRelationshipVO chainRelationship) {
		return page.setRecords(baseMapper.selectChainRelationshipPage(page, chainRelationship));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchUpdateStatus(List<ChainRelationship> chainRelationships, List<ChainSource> sources){
		List<ChainRelationship> preChainRelationships = chainRelationshipMapper.selectList(null);
		chainRelationships.forEach(x->{
			ChainRelationship temp = new ChainRelationship();
			temp.setId(x.getId());
			temp.setStatus(x.getStatus());
			chainRelationshipMapper.updateById(temp);
		});

		LocalDateTime localDateTime = LocalDateTime.now();
		String createTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss"));
		LOGGER.info("chainRelationships"+JSON.toJSONString(chainRelationships));
		LOGGER.info("preChainRelationships"+JSON.toJSONString(preChainRelationships));
		LOGGER.info("sources"+JSON.toJSONString(sources));
		chainRelationships.forEach(x->{
			preChainRelationships.forEach(p->{
				if(x.getId().equals(p.getId())){
					//之前状态正常，现在状态存在问题
					if(p.getStatus().equals(1)&&x.getStatus().equals(0)){
						Alerts defaultAlert = getDefaultAlert();
						defaultAlert.setSubject("Problem: 链路阻塞");
						defaultAlert.setMessage("hostName:::"+p.getTargetName()+" |||\n" +
							"hostIP:::"+ p.getIp() +" |||\n" +
							"eventSeverity:::4 |||\n" +
							"eventName:::"+transferSourceId2Name(sources,x.getSourceId())+"到"+x.getTargetName()+"链路阻塞 |||\n" +
							"eventTime:::"+createTime+" |||");
						alertsMapper.insert(defaultAlert);
					}
				}
			});
		});
	}

	private static String transferSourceId2Name(List<ChainSource> sources,Integer sourceId){
		Optional<ChainSource> first = sources.stream().filter(x ->
			 x.getId().equals(sourceId)
		).findFirst();
		return first.get().getSourceName();
	}

}
